﻿using System.IO;

/// <summary>
/// 上传实际处理类
/// lyh
/// 2014-10-27
/// </summary>
public class UploadFileHandler : UploadBaseHandler
{
    public string FileUploadPhysicalPath
    {
        get
        {
            if (fileUploadPhysicalPath.StartsWith("~"))
                fileUploadPhysicalPath = Context.Server.MapPath(fileUploadPhysicalPath);
            return fileUploadPhysicalPath;
        }
        set
        {
            fileUploadPhysicalPath = value;
        }
    }
    private string fileUploadPhysicalPath = "~/temp/";

    public UploadFileHandler()
    {

    }

    protected override bool OnUploadChunk(Stream chunkStream, int chunk, int chunks, string fileName)
    {
        var path = FileUploadPhysicalPath;
        if (!Directory.Exists(path))
        {
            try
            {
                Directory.CreateDirectory(path);
            }
            catch
            {
                var result = new Result()
                {
                    StatusCode = 500,
                    Title = "目录错误。",
                    Message = "上传目录不存在或无法创建目录"
                };
                WriteResponse(result);
                return false;
            }
        }

        fileName = Path.GetFileName(fileName);
        var uploadFilePath = Path.Combine(path, fileName);
        if (chunk == 0)
        {
            if (File.Exists(uploadFilePath))
                File.Delete(uploadFilePath);
        }

        try
        {
            using (var stream = new FileStream(uploadFilePath, (chunk == 0) ? FileMode.CreateNew : FileMode.Append))
            {
                chunkStream.CopyTo(stream);
            }
        }
        catch
        {
            var result = new Result()
            {
                StatusCode = 500,
                Title = "保存文件错误。",
                Message = "无法保存文件"
            };
            WriteResponse(result);
            return false;
        }

        return true;
    }
}